﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Xml.Serialization;
using System.IO;


public partial class Client : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Call for a specific truc lon lat
        if (!IsPostBack && !String.IsNullOrEmpty(Page.Request.QueryString["asktrucklonlat"]))
        {
            GiveTruckLonLat(Page.Request.QueryString["asktrucklonlat"]);
        }
        // Call for a specific truc lon lat in an AJAX style
        if (!IsPostBack && !String.IsNullOrEmpty(Page.Request.QueryString["ajaxtruckid"]))
        {
            AjaxGiveTruckLonLat();
        }
    }

    /// <summary>
    /// Return a truck specific lon lat
    /// </summary>
    private string GiveTruckLonLat(string truckID)
    {
        string retour = "";
        string strAccessSelect = "SELECT Latitude, Longitude FROM tblPosition WHERE IDCamion = " + truckID;

        try
        {
            DataTable table = executeQuery(strAccessSelect);
            retour = table.Rows[0]["Longitude"].ToString() + ";" + table.Rows[0]["Latitude"].ToString();
        }
        catch (Exception ee)
        {
            Trace.Warn("GiveTruckLonLat", "Error in database query : " + ee.Message);
            throw new Exception("Error in Client.aspx in GiveTruckLonLat() function");
        }
        hiddenPosText.Text = retour;

        return retour;
    }

    // Execute all query
    private DataTable executeQuery(string strAccessQuery)
    {
        string strAccessCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\gpsserver\\navigateur.mdb";
        DataTable table = new DataTable();
        OleDbConnection dbCon = new OleDbConnection(strAccessCon);
        OleDbCommand dbCom = new OleDbCommand(strAccessQuery, dbCon);
        OleDbDataAdapter dbDat = new OleDbDataAdapter(dbCom);
        try
        {
            dbCon.Open();
            dbDat.Fill(table);
            dbCon.Close();
            return table;
        }
        catch (Exception e)
        {
            Trace.Warn("Database Query Error","Error while executing query : " + e.Message);
            dbCon.Close();
            return null;
        }
    }

    // If Ajax query, send only a truck position then stop messaging in order to
    // block the remaining (map etc) page content
    private void AjaxGiveTruckLonLat()
    {
        string lonlat = GiveTruckLonLat(Page.Request.QueryString["ajaxtruckid"]);
        Response.Write(lonlat);
        Response.End();
    }
}